import React, { useEffect, useRef, useImperativeHandle } from 'react';
import humanData from '../assets/555.png';

const DigitalHuman = ({ ref }) => {
    const canvasRef = useRef(null);
    let image = useRef(null);
    // 容器（框架）的大小
    const frameWidth = 384;
    const frameHeight = 576;
    // 图片有几帧
    const frameCount = 4;
    // 显示第几帧
    let currentFrame = useRef(0);

    let lastTime = 0;
    const fps = 10;
    const timer = useRef(null);
    const ctx = useRef(null);

    // 是否停止播放
    const isStop = useRef(false);

    useEffect(() => {
        ctx.current = canvasRef.current.getContext('2d');
        image.current = new Image();
        image.current.onload = () => {
            // 图片加载完绘制第一帧
            ctx.current.drawImage(
                image.current,
                0, 0,
                512, 768,
                0, 0,
                frameWidth, frameHeight
            );
        };
        image.current.src = humanData;
    }, []);


    function animate(time) {
        if (time - lastTime > 1000 / fps) {
            ctx.current.clearRect(0, 0, frameWidth, frameHeight);

            var w = 0;
            var h = 0;
            if (currentFrame.current > 1) {
                h = 744;
            }
            if (currentFrame.current == 1 || currentFrame.current == 3) {
                w = 460;
            }

            ctx.current.drawImage(
                image.current,
                w, h,                       // sx, sy
                512, 768,                   // sw, sh
                0, 0,                       // dx, dy
                frameWidth, frameHeight     // dw, dh
            );
            currentFrame.current = (currentFrame.current + 1) % frameCount;
            lastTime = time;
        }

        if (isStop.current && currentFrame.current === 1) {
            cancelAnimationFrame(timer.current);
            timer.current = null;
        } else {
            timer.current = requestAnimationFrame(animate);
        }
    }

    function play() {
        isStop.current = false;
        timer.current = requestAnimationFrame(animate);
    }


    // 一个完整的播放是4帧，如果不到4帧需要播放完，然后停在第一帧
    function stop() {
        isStop.current = true;
    }

    useImperativeHandle(ref, () => {
        return {
            stop,
            play
        };
    }, []);

    return (
        <div className='flex flex-col'>
            <div className='overflow-hidden'>
                <canvas ref={canvasRef} width={frameWidth} height={frameHeight} className='-mt-7 -ml-20'></canvas>
            </div>
            {/* <div className='mt-20'></div>
            <button onClick={() => play()}>play</button>
            <div className='mb-2'></div>
            <button onClick={() => stop()}>stop</button> */}
        </div>
    );
};

export default DigitalHuman;